import traceback

from lxml import etree

from spider import spiders

brand_list = []  # 品牌列表


# 入口
def exec():
    global brand_list

    # 获取品牌列表
    if len(brand_list) == 0:
        resp = spiders.get_html('http://localhost/st/index.html')
        parse(resp)

    # 获取车型列表
    fetch_car_prices()

    print("任务完成！")
    print(brand_list)
    return brand_list


# 解析页面
def parse(resp):
    global brand_list

    try:
        html = resp.text
        tree = etree.HTML(html)

        tree_root = tree.xpath("//div[@id='cartree']")[0]
        list = tree_root.xpath(".//a")
        parse_brand(list)

    except Exception as err:
        print(err, traceback.print_exc())
        return "error: $Exception"


# 解析单个品牌节点
def parse_brand(list):
    global brand_list
    brand_list.clear()
    id = 0
    for x in list:
        # 页面链接
        link = x.get("href")

        # 品牌名称
        name = x.xpath("string()").strip()

        index = name.rfind("(")  # 从右侧查找最后一个左括号
        if (index > 0):
            name = name[:index]

        id += 1

        # 品牌记录
        brand = dict()
        brand['id'] = id
        brand['name'] = name
        brand['link'] = link

        # 添加到品牌列表
        brand_list.append(brand)


# 收集汽车价格
def fetch_car_prices():
    global brand_list
    n = 0

    for brand in brand_list:
        try:
            # 获取车型页面
            print(brand['link'])
            resp = spiders.get_html(brand['link'])
            car_list = parse_car_price(resp)

            brand['cars'] = car_list

        except Exception as err:
            print(err, traceback.print_exc())


# 收集单一品牌各车型价格
def parse_car_price(resp):
    html = resp.text
    tree = etree.HTML(html)

    list = tree.xpath("//div[@class='list-cont-main']")
    car_list = []

    for x in list:
        typeNode = x.xpath(".//a[@class='font-bold']")[0]
        type = typeNode.xpath("string()")

        priceNode = x.xpath(".//span[@class='font-arial']")[0]
        price = priceNode.xpath("string()")

        print(type, ": ", price)

        car = dict()
        car['type'] = type
        car['price'] = price
        car_list.append(car)

    return car_list
